<template>
  <div class="warehouse-container">
    <el-card>
      <div slot="header">
        <div class="flex justify-between items-center">
          <h2>仓库管理</h2>
          <el-button type="primary" @click="openAddDialog">
            <el-icon><Plus /></el-icon>新增仓库
          </el-button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="mb-4" @submit.prevent>
        <el-form-item label="仓库名称">
          <el-input v-model="searchForm.name" placeholder="请输入仓库名称" clearable />
        </el-form-item>
        <el-form-item label="仓库地址">
          <el-input v-model="searchForm.address" placeholder="请输入仓库地址" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchWarehouses">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 仓库列表 -->
      <el-table
          :data="warehouseList"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column prop="warehouseId" label="ID" width="80" />
        <el-table-column prop="name" label="仓库名称" />
        <el-table-column prop="address" label="仓库地址" />
        <el-table-column prop="employeeId" label="负责人ID" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="openEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row.warehouseId)"
                :disabled="scope.row.status === 0"
            >
              删除
            </el-button>
            <el-button
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                size="small"
                @click="handleDisable(scope.row)"
            >
              {{ scope.row.status === 1 ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          class="mt-4"
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑仓库对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form
          ref="warehouseForm"
          :model="warehouseForm"
          :rules="formRules"
          label-width="100px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="warehouseForm.name" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库地址" prop="address">
          <el-input v-model="warehouseForm.address" placeholder="请输入仓库地址" />
        </el-form-item>
        <el-form-item label="负责人ID" prop="employeeId">
          <el-input v-model="warehouseForm.employeeId" placeholder="请输入负责人ID" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import warehouse from "../api/warehouse.js";
export default {
  components: {
    Plus
  },
  data() {
    return {
      // 仓库列表数据
      warehouseList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      // 搜索表单
      searchForm: {
        name: '',
        address: ''
      },
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新增仓库',
      warehouseForm: {
        warehouseId: null,
        name: '',
        address: '',
        employeeId: null,
        status: 1
      },
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' },
          { max: 50, message: '仓库名称不能超过50个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入仓库地址', trigger: 'blur' },
          { max: 200, message: '仓库地址不能超过200个字符', trigger: 'blur' }
        ],
        employeeId: [
          { required: true, message: '请输入负责人ID', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getWarehouseList()
  },
  methods: {
    // 获取仓库列表
    async getWarehouseList() {
      try {
        const {data:data} = await warehouse.getAllWarehouses()
        // console.log(data)
        if (data.code === 200) {
          this.warehouseList = data.data
          this.total = data.data.length
        } else {
          this.$message.error(data.msg || '获取仓库列表失败')
        }
      } catch (error) {
        this.$message.error('获取仓库列表异常')
        console.error(error)
      }
    },
    // 搜索仓库
    async searchWarehouses() {
      try {
        const {data:data} = await warehouse.searchWarehouses(
            this.searchForm.name,
            this.searchForm.address
        )
        if (data.code === 200) {
          this.warehouseList = data.data
          this.total = data.data.length
        } else {
          this.$message.error(data.msg || '搜索仓库失败')
        }
      } catch (error) {
        this.$message.error('搜索仓库异常')
        console.error(error)
      }
    },
    // 重置搜索
    resetSearch() {
      this.searchForm.name = ''
      this.searchForm.address = ''
      this.getWarehouseList()
    },
    // 打开新增对话框
    openAddDialog() {
      this.dialogTitle = '新增仓库'
      this.warehouseForm = {
        warehouseId: null,
        name: '',
        address: '',
        employeeId: null
      }
      this.dialogVisible = true
    },
    // 打开编辑对话框
    openEditDialog(row) {
      this.dialogTitle = '编辑仓库'
      this.warehouseForm = {
        warehouseId: row.warehouseId,
        name: row.name,
        address: row.address,
        employeeId: row.employeeId,
        status: row.status
      }
      this.dialogVisible = true
    },
    // 提交表单
    async submitForm() {
      try {
        await this.$refs.warehouseForm.validate()


        if (this.warehouseForm.warehouseId) {
          // 更新仓库
          let {data:data} = await warehouse.updateWarehouse(this.warehouseForm)
          await this.getWarehouseList()
        } else {
          // 新增仓库
          let {data:data} = await warehouse.addWarehouse(this.warehouseForm)
          await this.getWarehouseList()
        }

        if (data.code === 200) {
          this.$message.success(data.msg || '操作成功')
          this.dialogVisible = false
          await this.getWarehouseList()
        } else {
          this.$message.error(data.msg || '操作失败')
        }
      } catch (error) {
        if (error.name === 'Error') {
          this.$message.error('操作异常')
          console.error(error)
        }
        // 表单验证失败不处理，会自动提示
      }
    },
    // 删除仓库
    async handleDelete(id) {
      try {
        await this.$confirm('确定要删除该仓库吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        let {data:data} = await warehouse.deleteWarehouse(id)
        console.log(data)
        if (data.code === 200) {
          this.$message.success('删除成功')
          await this.getWarehouseList()
        } else if (data.code === 409) {
          this.$message.error('该仓库已被引用，无法删除')
        } else {
          this.$message.error(data.msg || '删除失败')
        }
      } catch (error) {
        if (error === 'cancel') {
          return
        }
        this.$message.error('删除异常')
        console.error(error)
      }
    },
    async handleDisable(row) {
      try {
        const action = row.status === 1 ? '停用' : '启用'
        // 计算目标状态：1→0（停用），0→1（启用）
        const targetStatus = row.status === 1 ? 0 : 1

        await this.$confirm(`确定要${action}该仓库吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 关键：传递仓库ID和目标状态给后端
        let { data: data } = await warehouse.disableWarehouse({
          warehouseId: row.warehouseId,
          status: targetStatus
        })

        if (data.code === 200) {
          this.$message.success(`${action}成功`)
          await this.getWarehouseList()
        } else if (data.code === 409) {
          this.$message.error('该仓库已被引用，无法停用')
        } else {
          this.$message.error(data.msg || `${action}失败`)
        }
      } catch (error) {
        // 正确判断取消操作：Element Plus 取消时 error.name 为 'Cancel'
        if (error.name === 'Cancel') {
          return
        }
        this.$message.error('操作异常')
        console.error(error)
      }
    },
    // 分页变化
    handlePageChange(page) {
      this.currentPage = page
    }
  }
}
</script>

<style scoped>
.warehouse-container {
  padding: 20px;
}
</style>